/*
 * Equals field validator
 *  
 * Copyright (C) 2011 Antti Leppä / Otavan Opisto
 * http://www.otavanopisto.fi
 * 
 * License: 
 * 
 * Licensed under GNU Lesser General Public License Version 3 or later (the "LGPL") 
 * http://www.gnu.org/licenses/lgpl.html
 */
fi.internetix.validation.validator.EqualsFieldValidator = Class.create(fi.internetix.validation.LinkedFieldValidator,
  /** @lends fi.internetix.validation.validator.EqualsFieldValidator# **/   
  {
  /**
  * Class constructor
  * @class Constructs this class
  * @extends fi.internetix.validation.LinkedFieldValidator
  * @constructs
  * @param $super super class 
  */
  initialize : function($super) {
    $super();
  },
  validate: function ($super, field) {
    var equalsField = this.getLinkedField(field);
    if (equalsField) {
      var value1 = this._getFieldValue(field);
      var value2 = this._getFieldValue(equalsField);
      if (value1) 
        return value1 == value2 ? fi.internetix.validation.FieldValidator.STATUS_VALID : fi.internetix.validation.FieldValidator.STATUS_INVALID;
    } 
    
    return fi.internetix.validation.FieldValidator.STATUS_UNKNOWN;
  },
  getLinkedField: function (field) {
    var fieldClassNames = $w(field.className);
    var form = field.form;
    for (var i = 0, l = fieldClassNames.length; i < l; i++) {
      if (fieldClassNames[i].startsWith('equals-')) {
        var linkedFieldName = fieldClassNames[i].substring(7);
        if (form) {
          var equalsField = form[linkedFieldName];
          if (equalsField)
            return equalsField;
        } 

        var equalsFields = document.getElementsByName(linkedFieldName);
        if (equalsFields.length == 1) {
          return equalsFields[0];
        }
      }
    }
    
    return null;
  },
  getClassName: function () {
    return 'equals';
  }
});

fi.internetix.validation.FieldValidatorVault.registerValidator(new fi.internetix.validation.validator.EqualsFieldValidator());